package com.github.prontera.controller;

import java.io.File;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.prontera.ApiVersion;
import com.github.prontera.Shift;
import com.github.prontera.StatusCode;
import com.github.prontera.common.filter.CurrentUserId;
import com.github.prontera.common.filter.IgnoreAuth;
import com.github.prontera.config.ConfigUtil;
import com.github.prontera.domain.Activity;
import com.github.prontera.domain.ClientActivity;
import com.github.prontera.model.response.ObjectDataResponse;
import com.github.prontera.model.response.Response;
import com.github.prontera.service.ActivityService;
import com.github.prontera.service.ClientActivityService;
import com.github.prontera.util.FreeMarkerFactory;
import com.github.prontera.util.IdWorker;
import com.github.prontera.util.Page;

import cn.jiguang.common.utils.Base64;
import freemarker.template.TemplateException;
import io.swagger.annotations.ApiOperation;


/**
 * 活动
 */
@RestController
@RequestMapping(value = ApiVersion.MANAGE_V1_PREFIX + "/activity", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE }, consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public class ActivityController{

	@Autowired
	private ActivityService activityService;
	@Autowired
	private ClientActivityService clientActivityService;
	@Autowired
	private ConfigUtil configUtil;
	
	/**
	 * 查询活动列表
	 */
//	@ApiIgnore() //是否在swagger中显示此方法
	@IgnoreAuth
	@RequestMapping(value = "find", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查询活动列表" , notes = "查询活动列表")
	public  ObjectDataResponse<String> find(Activity activity){
		/*activity.setOrderBy("A_ACTIVITY.create_time desc");
		Page<Activity> datas =activityService.page(activity);*/
		String str="ok";
		return  new ObjectDataResponse<String>(str);
	}
	
	/**
	 * 查询活动用户列表
	 */
	
	@RequestMapping(value = "findClients", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查询活动用户列表" , notes = "查询活动用户列表")
	public ObjectDataResponse<Page<ClientActivity>> findClients(@RequestBody ClientActivity activity){
		activity.setOrderBy("A_CLIENT_ACTIVITY.create_time desc");
		Page<ClientActivity> datas =clientActivityService.page(activity);
		return new ObjectDataResponse<Page<ClientActivity>>(datas);
	}
	
	
//	/**
//	 * 删除活动
//	 */
//	@ApiOperation(value = "删除用户", notes = "删除用户")
//	@RequestMapping(value = "/deleteActivity", method = RequestMethod.POST)
//	@ResponseBody
//	public Response deleteActivity(@CurrentUserId Long userId, @RequestBody Activity activity) {
//		int success = activityService.remove(activity);
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("success", success);
//		if(success == 2){
//			map.put("msg", "删除活动失败！");	
//		}
//		return new ObjectDataResponse<Object>(map);
//	}
//	
	
	/**
	 *重新启动活动
	 */
	@ApiOperation(value = "重新启动活动", notes = "重新启动活动")
	@RequestMapping(value = "/startActivity", method = RequestMethod.POST)
	@ResponseBody
	public Response startActivity(@CurrentUserId Long userId, @RequestBody Activity activity) {
		Activity activity2=activityService.get(activity.getId());
		activity2.setStatus(0);
		if(activity2.getStartTime().isBefore(OffsetDateTime.now())){
			activity2.setStatus(1);
		}
		if(activity2.getApplicantsNumber()==activity2.getActualNumber()){
			activity2.setStatus(2);
		}
		if(activity2.getEndTime().isBefore(OffsetDateTime.now())){
			activity2.setStatus(3);
		}
		int success = activityService.update(activity2);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", success);
		if(success == 2){
			map.put("msg", "停止报名失败！");	
		}
		return new ObjectDataResponse<Object>(map);
	}
	
	
	/**
	 *停止报名
	 */
	@ApiOperation(value = "停止报名", notes = "停止报名")
	@RequestMapping(value = "/stopActivity", method = RequestMethod.POST)
	@ResponseBody
	public Response stopActivity(@CurrentUserId Long userId, @RequestBody Activity activity) {
		activity.setStatus(4);
		int success = activityService.update(activity);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", success);
		if(success == 2){
			map.put("msg", "停止报名失败！");	
		}
		return new ObjectDataResponse<Object>(map);
	}

	@ApiOperation(value = "修改活动", notes = "修改活动")
	@RequestMapping(value = "updateActivity", method = RequestMethod.POST)
	@ResponseBody
	public Response updateActivity(@CurrentUserId Long userId,@RequestBody Activity activity) {
		int success = activityService.update(activity);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", success);
		if(success == 2){
			map.put("msg", "修改活动失败！");
		}
		return new ObjectDataResponse<Object>(map);
	}
	
	@ApiOperation(value = "添加活动", notes = "添加活动")
	@RequestMapping(value = "addActivity", method = RequestMethod.POST)
	@ResponseBody
	public Response addDict(@CurrentUserId Long userId, @RequestBody Activity activity) throws IOException, TemplateException {
		if(activity.getStartTime()==null){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "开始时间 必填!");
		}
		if(activity.getEndTime()==null){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "结束时间 必填!");
		}
		if(activity.getApplicantsNumber()==null){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "可报名人数 必填!");
		}
		if(activity.getContent()==null){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "活动介绍 必填!");
		}
		if(activity.getHeadImages()==null){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "标题照片 必填!");
		}
		if(activity.getActivitySite()==null){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "活动场地 必填!");
		}
		if(activity.getStartTime().isBefore(OffsetDateTime.now())){
			activity.setStatus(1);
		}
		if(activity.getActualNumber()!=null&&activity.getApplicantsNumber()==activity.getActualNumber()){
			activity.setStatus(2);
		}
		if(activity.getEndTime().isBefore(OffsetDateTime.now())){
			activity.setStatus(3);
		}
		
		activity.setBaseAmount(activity.getDiscountAmount());
		activity.setVipAmount(activity.getDiscountAmount());
		
		String content=new String(Base64.decode(activity.getContent().toCharArray()));
		
		//<img class="img-responsive"
		content=content.replace("img src", "img class=\"img-responsive\" src");
		
		Map<String, Object> data=new HashMap<String, Object>();
		data.put("staticFileUrl", configUtil.getUploadAccessFilePath());
		data.put("content", content);
		data.put("title", activity.getActivityTheme());
		Resource resource = new ClassPathResource("/template");
		
		String filename=new IdWorker().getId()+".html";
		
		FreeMarkerFactory.createHTML("/data/project/manage2/template","activity.ftl", configUtil.getUploadAbsoluteFilePath()+File.separator+"html"+File.separator+filename, data);
		
		activity.setSummaryUrl(configUtil.getUploadAccessFilePath()+"html"+File.separator+filename);
		
		activity.setSummaryUrl(activity.getSummaryUrl().replace("\\","/"));
		
		int success = activityService.insert(activity);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", success);
		if(success == 2){
			map.put("msg", "新增活动失败！");
		}
		return new ObjectDataResponse<Object>(map);
	}
	
}
